﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Principal;
using FinWeb3.Models.Repository;

namespace FinWeb3.Models
{
    public class GroupManager
    {
        private IRepository<Group> repository;
        private IRepository<Bill> billRepository;
        private IIdentity user;


        public GroupManager(IRepository<Group> repository, IRepository<Bill> billRepository, IIdentity user)
        {
            this.repository = repository;
            this.billRepository = billRepository;
            this.user = user;
        }

        public List<Group> GetAll()
        {
            return 
                repository.GetAll(user)
                    .OrderBy(x => x.Description)
                    .ToList();
        }

        public virtual List<Group> Get(DateTime fromDate, DateTime toDate)
        {
            return 
                repository
                .GetAll(user)
                .Where(g => g.FirstDay <= toDate && (g.LastDay >= fromDate || g.LastDay == g.FirstDay))
                .ToList();
        }

        public Group Get(int id)
        {
            return repository.Get(id, user);
        }

        public void Save(Group group)
        {
            repository.Save(group, user);
        }

        public void Delete(int groupId)
        {
            var group = Get(groupId);

            if (group != null)
            {
                var billManager = new BillManager(billRepository, repository, user);
                var bills = billManager.Get(groupId, BillList.All);

                foreach (var bill in bills)
                {
                    bill.GroupId = null;
                    billManager.Save(bill);
                }

                repository.Delete(group, user); ;
            }
        }
    }
}
